package cn.edu.hzvtc.controller;

import cn.edu.hzvtc.entity.Employee;
import cn.edu.hzvtc.entity.ReturnMsg;
import cn.edu.hzvtc.service.DepartmentService;
import cn.edu.hzvtc.service.EmployeeService;
import cn.edu.hzvtc.util.ExportExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DepartmentService departmentService;

    @RequestMapping("/checkName")
    @ResponseBody
    public ReturnMsg checkName(@RequestParam("empName") String empName){
        String reg = "(^[a-zA-Z0-9]{6,13}$)|(^[\\u4e00-\\u9fa5]{2,6}$)";
        if(empName.equals("") || !empName.matches(reg)){
            return ReturnMsg.fail().add("fail_msg","姓名必须是2-6位中文或6-13位英文数字组合");
        }
        //检测姓名是否重名
        if(employeeService.checkEmpName(empName)){
            return ReturnMsg.success().add("success_msg","姓名可用");
        }else {
            return ReturnMsg.fail().add("fail_msg","姓名不可用");
        }

    }

    @RequestMapping(value = "/emp",method = RequestMethod.POST)
    @ResponseBody
    public ReturnMsg saveEmp(@Valid Employee employee, BindingResult result){
        if(!result.hasErrors()){
            if(employeeService.save(employee)){
                return ReturnMsg.success();
            }
        }
        ReturnMsg returnMsg = ReturnMsg.fail();
        //返回所有的错误信息
        for (FieldError error:result.getFieldErrors()){
            returnMsg.add(error.getField(),error.getDefaultMessage());
        }
        return returnMsg;
    }

    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id,Map<String,Object> map){
        if(id.contains("-")){
            String[] s = id.split("-");
            map.put("empId",s[0]);
            map.put("pn",s[1]);
        }
        return "edit";
    }

    @RequestMapping(value = "/emp/{id}",method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getEmp(@PathVariable("id") Integer id){
        Employee employee = employeeService.getEmp(id);
        return ReturnMsg.success().add("emp",employee);
    }

    @RequestMapping(value = "/emp/{empId}",method = RequestMethod.PUT)
    @ResponseBody
    public ReturnMsg updateEmp(@Valid Employee employee,BindingResult result){
        if(result.hasErrors()){
            Map<String,Object> map = new HashMap<String, Object>();
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError error : errors){
                map.put(error.getField(),error.getDefaultMessage());
            }
            return ReturnMsg.fail().add("fieldErrors",map);
        }else {
            employeeService.updateEmp(employee);
            return ReturnMsg.success();
        }
    }


    @RequestMapping("/list")
    public String list(@RequestParam(value = "pn",required = false,defaultValue = "1") Integer pn,
                       Map<String,Object> map){
        map.put("pn",pn);
        return "list";
    }

    @RequestMapping("/input")
    public String input(){
        return "input";
    }

    @RequestMapping(value = "/emp/{ids}", method = RequestMethod.DELETE)
    @ResponseBody
    public ReturnMsg deleteEmp(@PathVariable("ids") String ids) {

        if (employeeService.del(ids)) {
            return ReturnMsg.success();
        }
        return ReturnMsg.fail();
    }

    @RequestMapping("/emps")
    @ResponseBody
    public ReturnMsg getEmps(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        PageHelper.startPage(pn, 10);
        List<Employee> employees = employeeService.getAll();
        PageInfo pageInfo = new PageInfo(employees, 5);

        return ReturnMsg.success().add("pageInfo", pageInfo);
    }


    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        employeeService.export(response);
    }

}
